﻿/*
* Copyright (c) 2010-2012 Tesla Engine Group
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

using System.IO;

namespace Tesla.Content.Loaders {
    /// <summary>
    /// Loader for Tesla Engine Binary Object (TEBO) files.
    /// </summary>
    public class BinaryLoader : ResourceLoader<ISavable> {
        //TEBO magic word
        private static readonly byte[] MagicWord = new byte[] { 84, 69, 66, 79 };
        //Version number
        private static readonly byte VersionNumber = 1;

        /// <summary>
        /// Initializes a new instance of the <see cref="BinaryLoader"/> class.
        /// </summary>
        public BinaryLoader() 
            : base(".tebo") {
        }

        /// <summary>
        /// Loads the specified input stream containing the TEBO file.
        /// </summary>
        /// <param name="input">The input stream.</param>
        /// <exception cref="System.IO.InvalidDataException">Thrown if the stream does not contain a valid TEBO file.</exception>
        /// <returns>The loaded savable</returns>
        public ISavable Load(Stream input) {
            //Read header
            if(!ReadHeader(input)) {
                throw new InvalidDataException("Invalid binary file, either it is not a tesla engine binary object or the version is not compatible.");
            }

            BinarySavableReader reader = new BinarySavableReader(input, ContentManager);
            ISavable savable = reader.ReadSavable<ISavable>();
            reader.Dispose();
            return savable;
        }

        /// <summary>
        /// Loads the specified resource.
        /// </summary>
        /// <param name="resource">The resource to load</param>
        /// <param name="parameters">Any loading parameters</param>
        /// <exception cref="System.IO.InvalidDataException">Thrown if the stream does not contain a valid TEBO file.</exception>
        /// <returns>The loaded resource</returns>
        public override ISavable Load(IResource resource, LoaderParameters parameters) {
            //Read header
            Stream stream = resource.OpenStream();
            if(!ReadHeader(stream)) {
                throw new InvalidDataException("Invalid binary file, either it is not a tesla engine binary object or the version is not compatible.");
            }

            BinarySavableReader reader = new BinarySavableReader(stream, ContentManager);
            ISavable savable = reader.ReadSavable<ISavable>();
            reader.Dispose();
            return savable;
        }

        private bool ReadHeader(Stream stream) {
            stream.Position = 0;
            byte[] magic = new byte[4];
            stream.Read(magic, 0, 4);
            if(!CheckMagicWord(magic)) {
                return false;
            }
            if((byte)stream.ReadByte() != VersionNumber) {
                return false;
            }
            return true;
        }

        private bool CheckMagicWord(byte[] bytes) {
            if(bytes[0] == MagicWord[0] 
                && bytes[1] == MagicWord[1]
                && bytes[2] == MagicWord[2]
                && bytes[3] == MagicWord[3]) {
                return true;
            }
            return false;
        }
    }
}
